package zhjh;

import java.awt.image.*;
import java.io.*;
import java.util.BitSet;

public class BadApple {
	private InputStream in;
	private PrintWriter out;
	public static void main(String[] args) throws FileNotFoundException{
		// 4 * 60 * 15 = 3600
		// 90 * 40
		for (int i=0; i<40; i++){
			int start = i * 90;
			int end = (i + 1) * 90;
			if (i == 40) {
				end = 0;
			}
			task(i, start, end);
		}
	}
	public static void task(int i, int start, int end) throws FileNotFoundException{
		String path = String.format("BadApple!!%0$d.js", i);
		path = "D:\\BadApple!!\\"+ path;
		OutputStream out = new FileOutputStream(path);
		BadApple ba = new BadApple(
				BadApple.class.getResourceAsStream("BadApple!!.gif"),
				new PrintWriter(out));
		ba.process(start, end);
	}
	public BadApple(InputStream in, PrintWriter out){
		this.in = in;
		this.out = out;
	}
	void process(final int start, final int end){
		final GifDecoder gd = new GifDecoder();
		gd.setFilter(new ReadImageFilter() {
			int i = 0;
			public boolean filter(BufferedImage image) {
				if (start != 0 && i < start) {
					i ++;
					return true;
				}
				if (end != 0 && i >= end) {
					i ++;
					return true;
				}
				processFrame(image);
				out.print(",");
				out.println();
				i ++;
				return true;
			}
		});
		out.println("window.__bad_apple_frames = [");
		gd.read(in);
		out.println("null];");
		out.flush();
	}
	void processFrame(BufferedImage frameImage){
		out.print("[");
		int l = 0;
		boolean lastBit = false;
		for (int r=0, nr=frameImage.getHeight(); r<nr; r++) {
			for (int c=0, nc=frameImage.getWidth(); c<nc; c++) {
				int rgb = frameImage.getRGB(c, r);
				boolean bit = (rgb & 0x00808080) != 0;
				if (lastBit ^ bit) {
					lastBit = bit;
					out.print(l);
					out.print(",");
					l = 0;
				}
				l ++;
			}
		}
		out.print(l);
		out.print("]");
	}
	static int[] bits2Ints(BitSet bs) {
		int[] temp = new int[bs.size() / 32];

		for (int i = 0; i < temp.length; i++)
			for (int j = 0; j < 32; j++)
				if (bs.get(i * 32 + j))
					temp[i] |= 1 << j;

		return temp;
	}
}
